package com.atguigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.acl.helper.PermissionHelper;
import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.acl.service.RolePermissionService;
import com.atguigu.ssyx.model.acl.Permission;
import com.atguigu.ssyx.model.acl.RolePermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 权限服务实现类
 * </p>
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
												implements PermissionService {

	@Resource
	private RolePermissionService rolePermissionService;

	@Override
	public List<Permission> selectPermissionByRoleId(Long roleId) {
		//先查出所有权限列表
		List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));

		//根据角色id查询角色已有权限表
		LambdaQueryWrapper<RolePermission> wrapper=new LambdaQueryWrapper<>();
		wrapper.eq(RolePermission::getRoleId,roleId);
		List<RolePermission> rolePermissionList = rolePermissionService.list(wrapper);

		//将已有权限标记为选中状态
		for (RolePermission rolePermission:rolePermissionList) {
			Long permissionId = rolePermission.getPermissionId();
			for (Permission permission:allPermissionList) {
				if (permission.getId()==permissionId){
					permission.setSelect(true);
					break;
				}
			}
		}
		//把权限数据构建成树形结构数据
		List<Permission> result = PermissionHelper.bulid(allPermissionList);
		return result;
	}

	@Override
	public List<Permission> queryAllMenu() {
		//获取全部权限数据
		List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));

		//把权限数据构建成树形结构数据
		List<Permission> result = PermissionHelper.bulid(allPermissionList);
		return result;
	}

	@Override
	public boolean removeChildById(Long id) {
		List<Long> idList = new ArrayList<>();
		this.selectChildListById(id, idList);
		idList.add(id);
		baseMapper.deleteBatchIds(idList);
		return true;
	}
	/**
	 *	递归获取子节点
	 * @param id
	 * @param idList
	 */
	private void selectChildListById(Long id, List<Long> idList) {
		List<Permission> childList = baseMapper.selectList(new QueryWrapper<Permission>().eq("pid", id).select("id"));
		childList.stream().forEach(item -> {
			idList.add(item.getId());
			this.selectChildListById(item.getId(), idList);
		});
	}
}